package com.zhaiker.genderagelibrary

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.cv.tnn.model.Detector
import com.cv.tnn.model.FrameInfo
import com.zhaiker.object_detection_tnn.GenderAgeHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStream

class MainActivity : AppCompatActivity() {

    companion object{
        private const val score_threshold = 0.5f
        private const val iou_threshold = 0.5f
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        CoroutineScope(Dispatchers.Main).launch {
            GenderAgeHelper.init(this@MainActivity)
        }

        findViewById<Button>(R.id.btn).setOnClickListener {
            lifecycleScope.launch {
                if(!GenderAgeHelper.sdkAvailable) return@launch
                val bmp = getBitmapFromAssets(this@MainActivity, "test.png")
                val attr = detectFaceAttr(bmp!!)
                Log.d("MainActivity", "attr: ${attr.toString()}")
                Toast.makeText(this@MainActivity, "attr: ${attr.toString()}", Toast.LENGTH_SHORT).show()
            }
        }

    }

    /**
     * 读取Assets的图片
     */
    private suspend fun getBitmapFromAssets(context: Context, fileName: String): Bitmap? = withContext(Dispatchers.IO){
        var inputStream: InputStream? = null
        var bitmap: Bitmap? = null

        try {
            // 打开assets目录中的文件流
            inputStream = context.assets.open(fileName)
            // 将流解码为Bitmap
            bitmap = BitmapFactory.decodeStream(inputStream)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                inputStream?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        return@withContext bitmap
    }

    /**
     * 基于tnn的人脸检测性别和年龄，文章链接
     * https://blog.csdn.net/guyuealian/article/details/135556824
     */
    /**
     * 基于tnn的人脸检测性别和年龄，文章链接
     * https://blog.csdn.net/guyuealian/article/details/135556824
     */
    suspend fun detectFaceAttr(bitmap: Bitmap) : FaceAttr? = withContext(Dispatchers.IO){
        //maskBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        val result : Array<FrameInfo> = GenderAgeHelper.detect(bitmap, score_threshold, iou_threshold)
        if(result.isNullOrEmpty()){
            return@withContext null
        }else{
            val faceInfo : FrameInfo = result[0]
            val age = faceInfo.age
            val gender = if(faceInfo.gender == 0) "F" else "M"
            return@withContext FaceAttr(age,gender,faceInfo.rect)
        }

    }

}